﻿// PathHelper.cs
//
// Copyright (c) 2008 Mike Strobel
//
// This source code is subject to the terms of the Microsoft Reciprocal License (Ms-RL).
// For details, see <http://www.opensource.org/licenses/ms-rl.html>.
//
// All other rights reserved.

using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;

namespace Supremacy.Resources
{
    public static class PathHelper
    {
        private static readonly Lazy<string> _workingDirectory = new Lazy<string>(GetWorkingDirectoryCore);

        public static string GetWorkingDirectory()
        {
            return _workingDirectory.Value;
        }

        private static string GetWorkingDirectoryCore()
        {
            try
            {
                AppDomain.CurrentDomain.Load("SupremacyWPF");
                var designerType = Type.GetType("Supremacy.Client.Designer, SupremacyWPF", false);
                if (designerType != null)
                {
                    var isInDesignModeProperty = designerType.GetProperty(
                        "IsInDesignMode",
                        BindingFlags.Public | BindingFlags.Static);

                    if ((isInDesignModeProperty != null) && (bool)isInDesignModeProperty.GetValue(null, null))
                    {
                        var homePath = Environment.GetEnvironmentVariable(
                            "SupremacyRoot",
                            EnvironmentVariableTarget.User);

                        if (!string.IsNullOrWhiteSpace(homePath))
                            return homePath;
                    }
                }
            }
            catch {}

            return Environment.CurrentDirectory;
        }
    }
}
